package com.dragon.modules.yuegou.service.impl.busd;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.entity.busd.DistrictEntity;
import com.dragon.modules.yuegou.entity.busd.GroupEntity;
import com.dragon.modules.yuegou.entity.system.AddressEntity;
import com.dragon.modules.yuegou.enums.busd.DistrictIsContract;
import com.dragon.modules.yuegou.enums.busd.DistrictStatus;
import com.dragon.modules.yuegou.enums.busd.GroupStatus;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.code.PayCode;
import com.dragon.modules.yuegou.enums.system.ApplicationType;
import com.dragon.modules.yuegou.mapper.busd.DistrictMapper;
import com.dragon.modules.yuegou.model.busd.District;
import com.dragon.modules.yuegou.model.busd.WithdrawConfig;
import com.dragon.modules.yuegou.model.system.Application;
import com.dragon.modules.yuegou.query.busd.DistrictQuery;
import com.dragon.modules.yuegou.query.busd.GroupQuery;
import com.dragon.modules.yuegou.service.Sequence;
import com.dragon.modules.yuegou.service.busd.DistrictService;
import com.dragon.modules.yuegou.service.busd.GroupService;
import com.dragon.modules.yuegou.service.busd.WithdrawConfigService;
import com.dragon.modules.yuegou.service.system.AddressService;
import com.dragon.modules.yuegou.service.system.ApplicationService;
import com.dragon.modules.yuegou.web.Check;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商圈表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-19 08:59:40
 * @version 2.0
 */
@Service("busdDistrictService")
public class DistrictServiceImpl extends ServiceImpl<DistrictMapper, DistrictEntity> implements DistrictService {

	@Autowired
	private ApplicationService applicationService;

	@Autowired
	private AddressService addressService;

	@Autowired
	private GroupService groupService;

	@Autowired
	private WithdrawConfigService withdrawConfigService;

	@Autowired
	private Sequence sequence;

	@Transactional
	@Override
	public void saveBus(District district) {
		// 获取集团信息
		GroupEntity group = groupService.getById(district.getGroupId());
		if (group.getBusdQuantity() <= 0 || group.getUserQuantity() <= 0) {
			throw new DragonException(BusinessCode.DISTRICT_ERRO_GROUP);
		}
		DistrictQuery districtQuery = new DistrictQuery();
		districtQuery.setBcName(district.getBcName());
		if (StringUtils.isNotEmpty(district.getId())) {
			List<DistrictEntity> list = baseMapper.selectList(districtQuery.toQueryWrapper());
			if (list.size() > 0 && !list.get(0).getId().equals(district.getId())) {
				throw new DragonException(BusinessCode.DISTRICT_NAME_EXISTS);
			}
			// 修改商圈信息
			baseMapper.updateById(district);
		} else {
			// 获取集团下商圈数量
			DistrictQuery query = new DistrictQuery();
			query.setGroupId(district.getGroupId());
			query.setDel(false);
			Long groupCount = baseMapper.selectCount(query.toQueryWrapper());

			// 判断集团下的商圈是否大于等于商圈数量的最大限制
			if (groupCount >= group.getBusdQuantity()) {
				throw new DragonException(BusinessCode.BOUDS_GROUP_SUM);
			}

			// 判断商圈名是否已存在
			Long count = baseMapper.selectCount(districtQuery.toQueryWrapper());
			if (count > 0) {
				throw new DragonException(BusinessCode.DISTRICT_NAME_EXISTS);
			}
			// 插入商圈信息
			district.setStatus(DistrictStatus.ENABLED);
			district.setId(sequence.nextBusdId());
			baseMapper.insert(district);

			WithdrawConfig withdrawConfig = new WithdrawConfig();
			withdrawConfig.setBusdId(district.getId());
			withdrawConfigService.save(withdrawConfig);
		}
	}

	@Override
	public void busLicense(District district) {
		baseMapper.updateById(district);
	}

	@Override
	public void endisableBus(String busId, DistrictStatus districtStatus) {
		DistrictEntity district = baseMapper.selectById(busId);
		district.setStatus(districtStatus);
		baseMapper.updateById(district);
	}

	@Override
	public List<District> getDistrict() {
		DistrictQuery districtQuery = new DistrictQuery();
		districtQuery.setStatus(DistrictStatus.ENABLED);
		List<DistrictEntity> list = baseMapper.selectList(districtQuery.toQueryWrapper());
		return list.stream().map(District::new).collect(Collectors.toList());
	}

	@Override
	public List<District> getGroupDistrict(String groupId) {
		DistrictQuery districtQuery = new DistrictQuery();
		districtQuery.setGroupId(groupId);
		districtQuery.setStatus(DistrictStatus.ENABLED);
		List<DistrictEntity> list = baseMapper.selectList(districtQuery.toQueryWrapper());
		return list.stream().map(District::new).collect(Collectors.toList());
	}

	@Override
	public List<District> findListByLAL(String appid) {
		Check.notNull(appid, "appid不能为空");
		Application application = applicationService.getByAppid(appid);

		GroupQuery groupQuery = new GroupQuery();
		DistrictQuery query = new DistrictQuery();
		query.setDel(false);

		if (application.getType().getCode() == ApplicationType.ANDROID.getCode()
				|| application.getType().getCode() == ApplicationType.IOS.getCode()) {
			return findAppList(groupQuery,application,query);
		} else if (application.getType().getCode() == ApplicationType.WALLET.getCode()) {
			// 悦荷包
			query.setStatus(DistrictStatus.ENABLED);
			List<DistrictEntity> districtList = this.list(query.toQueryWrapper());
			return districtList.stream().map(District::new).collect(Collectors.toList());
		} else if (application.getType().getCode() == ApplicationType.YSQ.getCode()) {
			// 悦商圈
			List<DistrictEntity> districtList = this.list(query.toQueryWrapper());
			return districtList.stream().map(District::new).collect(Collectors.toList());
		} else if (application.getType().getCode() == ApplicationType.YGIRL.getCode()) {
			groupQuery.setMiniAppid(application.getAppid());
			groupQuery.setStatus(GroupStatus.ENABLED);
			List<GroupEntity> groupList = groupService.list(groupQuery.toQueryWrapper());
			if (groupList != null && groupList.size() > 0) {
				query.groupId().in(groupList.stream().map(GroupEntity::getId).collect(Collectors.toList()));
				// 悦购
				query.setStatus(DistrictStatus.ENABLED);
				query.setMini(true);
				List<DistrictEntity> districtList = this.list(query.toQueryWrapper());
				if (districtList != null && districtList.size() > 0) {
					return districtList.stream().map(District::new).collect(Collectors.toList());
				}
			}

			query = new DistrictQuery();
			query.setDel(false);
			query.setStatus(DistrictStatus.ENABLED);
			query.setMini(true);
			List<DistrictEntity> districtList = this.list(query.toQueryWrapper());
			return districtList.stream().map(District::new).collect(Collectors.toList());
		} else if (application.getType().getCode() == ApplicationType.ALIXCX.getCode()) {
			query = new DistrictQuery();
			query.setDel(false);
			query.setStatus(DistrictStatus.ENABLED);
			query.setMini(true);
			query.setAliAppId(application.getAppid());
			List<DistrictEntity> districtList = this.list(query.toQueryWrapper());
			return districtList.stream().map(District::new).collect(Collectors.toList());
		}
		return null;
	}

	private List<District> findAppList(GroupQuery groupQuery,Application application,DistrictQuery query){
		// app
		groupQuery.setAppId(application.getAppid());
		groupQuery.setStatus(GroupStatus.ENABLED);
		List<GroupEntity> groupList = groupService.list(groupQuery.toQueryWrapper());
		if (groupList == null || groupList.size() == 0) {
			return null;
		}

		query.groupId().in(groupList.stream().map(GroupEntity::getId).collect(Collectors.toList()));
		query.setApp(true);
		List<DistrictEntity> districtList = this.list(query.toQueryWrapper());
		return districtList.stream().map(District::new).collect(Collectors.toList());
	}

	@Override
	public District getDistrictById(String id) {
		Check.notNull(id, BusinessCode.BUSDID_NOTNULL.getMessage());
		DistrictEntity districtEntity = baseMapper.selectById(id);
		District district = new District(districtEntity);
		if (!StringUtils.isEmpty(district.getAreaCode())) {
			AddressEntity districtQ = addressService.getById(district.getAreaCode());
			AddressEntity districtS = addressService
					.getById(district.getAreaCode().substring(0, district.getAreaCode().length() - 4) + "0000");
			AddressEntity districtP = addressService
					.getById(district.getAreaCode().substring(0, district.getAreaCode().length() - 8) + "00000000");
			district.setArea(districtQ.getName());
			district.setCity(districtS.getName());
			district.setProvince(districtP.getName());
			district.setAreaId(districtQ.getId());
			district.setCityId(districtS.getId());
			district.setProvinceId(districtP.getId());
		}
		GroupEntity group = groupService.getById(district.getGroupId());
		district.setGroupName(group.getGroupName());
		return district;
	}

	@Override
	public String getAppId(String busdId) {
		return baseMapper.getAppId(busdId);
	}

	@Override
	public String getAliAppId(String busdId) {
		DistrictEntity district = baseMapper.selectById(busdId);
		if(null != district) {
			return district.getAliAppId();
		}
		return null;
	}
	
	@Override
	public Map<String, String> getAppIdMap(List<String> busdIdList) {
		Map<String, String> map = new HashMap<>();
		for (String busdId : busdIdList) {
			String appId = baseMapper.getAppId(busdId);
			map.put(busdId, appId);
		}
		return map;
	}

	@Override
	public List<District> findByGroupId(String groupId) {
		return baseMapper.findByGroupId(groupId);
	}

	@Override
	public void checkBusdId(String busdId) {
		if (StringUtils.isEmpty(busdId) || this.getById(busdId) == null) {
			throw new DragonException(PayCode.BUSD_IS_NOT_EXIST);
		}
	}

	@Override
	public List<District> findListByType(DistrictIsContract isContract) {
		DistrictQuery query = new DistrictQuery();
		query.setDel(false);
		query.setIsContract(isContract);
		List<DistrictEntity> districtList = this.list(query.toQueryWrapper());
		return districtList.stream().map(District::new).collect(Collectors.toList());
	}

}